import UIKit
import SVProgressHUD
import AFNetworking
class StatusListViewModel: NSObject {
    lazy var statues = [Status]()
    func load(isPullUp: Bool, finished: (isSuccess: Bool) -> ()) {
        
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel.sharedUserAccountViewModel.access_token else {
            SVProgressHUD.showErrorWithStatus("请登录")
            return
        }
        var parameters = ["access_token": token]
        var since_id: Int64 = 0
        var max_id: Int64 = 0
        
        if isPullUp {
            //小菊花正在转动,上拉加载更多数据
            max_id = self.statues.last?.id ?? 0
        }else {
            since_id = self.statues.first?.id ?? 0
        }
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            parameters["max_id"] = "\(max_id)"
        }
        let AFN = AFHTTPSessionManager()
        //发起GET请求
        
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            //将result转化为字典类型
            guard let dict = result as? [String: AnyObject] else {
                finished(isSuccess: false)
                return
            }
            //2.在字典中通过  "statuses"这个key 来去获取微博数组数据
            
            guard let array = dict["statuses"] as? [[String: AnyObject]] else {
               finished(isSuccess: false)
                return
            }
            //实例化模型数据
            var temparray = [Status]()
            //遍历数组 获取单个的字典对象
            for item in array {
                //print(item)
                //4.字典转模型
                let s = Status(dict: item)
                //5.将模型数据添加到数组中
                temparray.append(s)
            }
            //记录临时数组
            if since_id > 0 {
                //在数组前面进行添加操作的操作
                self.statues = temparray + self.statues
            }else if max_id > 0 {
                //上拉加载更多数据
                self.statues += temparray

            }else {
                //如果不是下拉刷新数据(首次加载数据)
                self.statues = temparray
            }

            //执行成功的回调
            finished(isSuccess: true)
            
            }) { (_, error) -> Void in
                finished(isSuccess: false)
                print(error)
        }
    }

}


